import Foundation
import MapKit
import SwiftUI

@Observable class LocationViewModel: Identifiable {
    var location: [Location]
    var mapLocation: Location {
        didSet {
            updateMapRegion(location: mapLocation)
        }
    }

    var mapRegin: MapCameraPosition = .region(MKCoordinateRegion())
    var mapSpan = MKCoordinateSpan(latitudeDelta: 0.1, longitudeDelta: 0.1)
    var showLocationList: Bool = false
    var showLocationDetail:Location? = nil

    init() {
        let location = LocationsDataService.locations
        self.location = location
        self.mapLocation = location.first!
        updateMapRegion(location: location.first!)
    }

    private func updateMapRegion(location: Location) {
        withAnimation(.easeInOut) {
            mapRegin = MapCameraPosition.region(MKCoordinateRegion(center: location.coordinates, span: mapSpan))
        }
    }

    func updateShowLocationList() {
        withAnimation(.easeInOut) {
            showLocationList.toggle()
        }
    }

    func updateNextLocation(location: Location) {
        withAnimation(.easeInOut) {
            mapLocation = location
            showLocationList = false
        }
    }

    func updateNextBtn() {
        guard let current = location.firstIndex(where: { $0 == mapLocation }) else {
            return
        }
        let nextIndex = current + 1
        // indices  数组有效索引（从0开始）
        // contains 包含nextIndex这个索引
        guard location.indices.contains(nextIndex) else {
            guard let firstLocation = location.first else { return }
            updateNextLocation(location: firstLocation)
            return
        }
        let nextLocation = location[nextIndex]
        updateNextLocation(location: nextLocation)
    }
}
